package main

import (
	"fmt"
	"github.com/panjf2000/ants/v2"
	"sync"
	"time"
)

var wg = sync.WaitGroup{}

func Producer(intChan chan<- int, product int) {
	fmt.Println("生产数据", product)
	time.Sleep(2 * time.Second)
	intChan <- product
}
func consumer(intChan <-chan int) {
	for {
		select {
		case product, ok := <-intChan:
			if !ok {
				fmt.Println("通道已关闭")
				return
			}
			fmt.Println("消费数据:", product)
		}
	}
}

func main() {
	var err error
	pool, err := ants.NewPool(10)
	if err != nil {
		panic(err)
	}
	defer pool.Release()
	intChan := make(chan int)
	wg.Add(1)
	pool.Submit(func() {
		defer wg.Done()
		for i := 0; i < 10; i++ {
			wg.Add(1)
			pool.Submit(func() {
				defer wg.Done()
				Producer(intChan, i)
				if i == 9 {
					close(intChan)
					fmt.Println("通道已关闭")
				}
			})
		}
	})
	wg.Add(1)
	pool.Submit(func() {
		defer wg.Done()
		consumer(intChan)
	})
	wg.Wait()
	fmt.Println("执行完成")
}
